<template>
  <div class="parent-layout">
    <div class="layout-container">
      <!-- 左侧菜单栏 -->
      <aside :class="['sidebar', { 'collapsed': sidebarCollapsed }]">
        <div class="toggle-btn" @click="toggleSidebar">
          <span>{{ sidebarCollapsed ? '›' : '‹' }}</span>
        </div>

        <nav class="menu-nav" v-show="!sidebarCollapsed">
          <ul>
            <!-- 家长根菜单 -->
            <li>
              <div class="root-menu-title">
                <span class="menu-icon">👨‍👩‍👧‍👦</span>
                <span class="menu-text">{{ $t('message.parentPanel') }}</span>
              </div>
              
              <!-- 孩子管理菜单 -->
              <ul class="submenu">
                <li>
                  <div class="menu-group">
                    <div class="menu-group-title" @click="toggleCategory('children')">
                      <span class="menu-icon">👶</span>
                      <span class="menu-text">{{ $t('message.childrenManagement') }}</span>
                      <span class="expand-icon" :class="{ expanded: isExpanded('children') }">▼</span>
                    </div>
                    <ul class="submenu" :class="{ hidden: !isExpanded('children') }">
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/children/list') }"
                          @click.prevent="handleMenuClick('/parent/children/list', $t('message.childrenList'))"
                        >
                          <span class="menu-icon">📋</span>
                          <span class="menu-text">{{ $t('message.childrenList') }}</span>
                        </a>
                      </li>
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/children/progress') }"
                          @click.prevent="handleMenuClick('/parent/children/progress', $t('message.childrenProgress'))"
                        >
                          <span class="menu-icon">📈</span>
                          <span class="menu-text">{{ $t('message.childrenProgress') }}</span>
                        </a>
                      </li>
                    </ul>
                  </div>
                </li>
                
                <!-- 预约管理菜单 -->
                <li>
                  <div class="menu-group">
                    <div class="menu-group-title" @click="toggleCategory('booking')">
                      <span class="menu-icon">📝</span>
                      <span class="menu-text">{{ $t('message.bookingManagement') }}</span>
                      <span class="expand-icon" :class="{ expanded: isExpanded('booking') }">▼</span>
                    </div>
                    <ul class="submenu" :class="{ hidden: !isExpanded('booking') }">
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/bookings/upcoming') }"
                          @click.prevent="handleMenuClick('/parent/bookings/upcoming', $t('message.upcomingBookings'))"
                        >
                          <span class="menu-icon">📅</span>
                          <span class="menu-text">{{ $t('message.upcomingBookings') }}</span>
                        </a>
                      </li>
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/bookings/history') }"
                          @click.prevent="handleMenuClick('/parent/bookings/history', $t('message.bookingHistory'))"
                        >
                          <span class="menu-icon">📋</span>
                          <span class="menu-text">{{ $t('message.bookingHistory') }}</span>
                        </a>
                      </li>
                    </ul>
                  </div>
                </li>
                
                <!-- 订单管理菜单 -->
                <li>
                  <div class="menu-group">
                    <div class="menu-group-title" @click="toggleCategory('order')">
                      <span class="menu-icon">🛒</span>
                      <span class="menu-text">{{ $t('message.orderManagement') }}</span>
                      <span class="expand-icon" :class="{ expanded: isExpanded('order') }">▼</span>
                    </div>
                    <ul class="submenu" :class="{ hidden: !isExpanded('order') }">
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/orders/pending') }"
                          @click.prevent="handleMenuClick('/parent/orders/pending', $t('message.pendingOrders'))"
                        >
                          <span class="menu-icon">⏳</span>
                          <span class="menu-text">{{ $t('message.pendingOrders') }}</span>
                        </a>
                      </li>
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/orders/history') }"
                          @click.prevent="handleMenuClick('/parent/orders/history', $t('message.orderHistory'))"
                        >
                          <span class="menu-icon">📦</span>
                          <span class="menu-text">{{ $t('message.orderHistory') }}</span>
                        </a>
                      </li>
                    </ul>
                  </div>
                </li>
                
                <!-- 优币管理菜单 -->
                <li>
                  <div class="menu-group">
                    <div class="menu-group-title" @click="toggleCategory('youbi')">
                      <span class="menu-icon">💰</span>
                      <span class="menu-text">{{ $t('message.youbi') }}</span>
                      <span class="expand-icon" :class="{ expanded: isExpanded('youbi') }">▼</span>
                    </div>
                    <ul class="submenu" :class="{ hidden: !isExpanded('youbi') }">
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/youbi/records') }"
                          @click.prevent="handleMenuClick('/parent/youbi/records', $t('message.youbiRecords'))"
                        >
                          <span class="menu-icon">📜</span>
                          <span class="menu-text">{{ $t('message.youbiRecords') }}</span>
                        </a>
                      </li>
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/youbi/recharge') }"
                          @click.prevent="handleMenuClick('/parent/youbi/recharge', $t('message.recharge'))"
                        >
                          <span class="menu-icon">💳</span>
                          <span class="menu-text">{{ $t('message.recharge') }}</span>
                        </a>
                      </li>
                    </ul>
                  </div>
                </li>
                
                <!-- 消息中心菜单 -->
                <li>
                  <div class="menu-group">
                    <div class="menu-group-title" @click="toggleCategory('message')">
                      <span class="menu-icon">💬</span>
                      <span class="menu-text">{{ $t('message.messages') }}</span>
                      <span class="expand-icon" :class="{ expanded: isExpanded('message') }">▼</span>
                    </div>
                    <ul class="submenu" :class="{ hidden: !isExpanded('message') }">
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/messages/notifications') }"
                          @click.prevent="handleMenuClick('/parent/messages/notifications', $t('message.notifications'))"
                        >
                          <span class="menu-icon">🔔</span>
                          <span class="menu-text">{{ $t('message.notifications') }}</span>
                        </a>
                      </li>
                      <li>
                        <a
                          href="#"
                          class="menu-item"
                          :class="{ active: isActiveMenu('/parent/messages/contact') }"
                          @click.prevent="handleMenuClick('/parent/messages/contact', $t('message.contactTeacher'))"
                        >
                          <span class="menu-icon">📞</span>
                          <span class="menu-text">{{ $t('message.contactTeacher') }}</span>
                        </a>
                      </li>
                    </ul>
                  </div>
                </li>
                
                <!-- 个人资料菜单 -->
                <li>
                  <a
                    href="#"
                    class="menu-item"
                    :class="{ active: isActiveMenu('/parent/profile') }"
                    @click.prevent="handleMenuClick('/parent/profile', $t('message.profile'))"
                  >
                    <span class="menu-icon">👤</span>
                    <span class="menu-text">{{ $t('message.profile') }}</span>
                  </a>
                </li>
              </ul>
            </li>
          </ul>
        </nav>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 标签页栏 -->
        <div class="tabs-bar">
          <div
            class="tab-item"
            :class="{ active: activeTab === '/parent' || activeTab === '/parent/profile' || openedTabs.length === 0 }"
            @click="switchToDefaultTab"
          >
            <span>{{ $t('message.profile') }}</span>
          </div>
          <div
            v-for="(tab, index) in openedTabs"
            :key="tab.name"
            class="tab-item"
            :class="{ active: activeTab === tab.name }"
            @click="switchTab(tab.name)"
          >
            <span>{{ tab.title }}</span>
            <span class="tab-close" @click.stop="closeTab(index)">×</span>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 默认标签内容（个人资料） -->
          <div v-if="isDefaultTabActive" class="tab-content">
            <div class="default-content">
              <router-view />
            </div>
          </div>

          <!-- 其他标签页的内容 -->
          <div
            v-for="tab in openedTabs"
            :key="tab.name"
            v-show="activeTab === tab.name"
            class="tab-content"
          >
            <div class="tab-content-inner">
              <router-view v-if="activeTab === tab.name" :key="tab.name" />
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';

export default {
  name: 'ParentLayout',
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const authStore = useAuthStore();

    // 侧边栏折叠状态
    const sidebarCollapsed = ref(false);
    
    // 展开的分类
    const expandedCategories = ref(new Set(['children', 'booking', 'message'])); // 默认展开部分分类

    // 标签页管理
    const openedTabs = ref([]);
    const activeTab = ref('');

    // 切换侧边栏收起/展开状态
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value;
    };

    // 展开/收起分类
    const toggleCategory = (category) => {
      if (expandedCategories.value.has(category)) {
        expandedCategories.value.delete(category);
      } else {
        expandedCategories.value.add(category);
      }
    };

    // 检查分类是否已展开
    const isExpanded = (category) => {
      return expandedCategories.value.has(category);
    };

    // 标签页激活检查
    const isDefaultTabActive = computed(() => {
      return activeTab.value === '/parent' ||
             activeTab.value === '/parent/profile' ||
             openedTabs.value.length === 0 ||
             !openedTabs.value.some(tab => tab.name === activeTab.value);
    });

    // 处理菜单点击
    const handleMenuClick = (menu) => {
      if (typeof menu === 'string') {
        // 如果传入的是路径字符串，则使用旧逻辑
        if (menu === '/parent' || menu === '/parent/profile') {
          switchToDefaultTab();
        } else {
          const menuName = menu.split('/').pop() || 'Dashboard';
          openTab(menu, t(`message.${menuName.toLowerCase()}`) || menuName);
        }
      } else {
        // 如果传入的是菜单对象，则使用新逻辑
        if (menu.menuUrl === '/parent' || menu.menuUrl === '/parent/profile') {
          switchToDefaultTab();
        } else if (!menu.children || menu.children.length === 0) {
          // 这是一个叶子菜单项，检查用户是否有权限访问
          if (isAccessibleRoute(menu.menuUrl)) {
            openTab(menu.menuUrl, menu.menuName);
          } else {
            // 显示无权限提示
            showPermissionDeniedAlert(menu.menuName);
          }
        } else {
          // 这是一个分类菜单，切换展开/收起状态
          toggleCategory(menu.menuId);
        }
      }
    };

    // 打开新标签页
    const openTab = async (name, title) => {
      // 检查是否已存在标签
      let existingTab = openedTabs.value.find(tab => tab.name === name);
      if (!existingTab) {
        openedTabs.value.push({ name, title });
        existingTab = { name, title }; // 更新引用
      }
      activeTab.value = name;

      // 导航到对应的路由
      if (route.path !== name) {
        await router.push({ path: name });
      }
    };

    // 切换当前标签页
    const switchTab = (name) => {
      activeTab.value = name;

      // 导航到对应的路由
      router.push({ path: name });
    };

    // 切换到默认标签页（个人资料）
    const switchToDefaultTab = () => {
      activeTab.value = '/parent/profile';
      router.push('/parent/profile');
    };

    // 关闭标签页
    const closeTab = (index) => {
      const tabToRemove = openedTabs.value[index];
      openedTabs.value.splice(index, 1);

      // 如果关闭的是当前激活的标签页，切换到默认标签页
      if (tabToRemove.name === activeTab.value) {
        switchToDefaultTab();
      }
    };

    // 检查菜单是否激活
    const isActiveMenu = (menuUrl) => {
      return activeTab.value === menuUrl;
    };

    // 检查用户是否有权限访问特定路由
    const isAccessibleRoute = (routePath) => {
      // 检查当前用户的角色和权限
      // 家长用户只能访问特定的路由
      if (!authStore.user) {
        return false; // 如果用户未登录，无权限
      }

      // 家长用户可以访问的路径
      const accessibleRoutes = [
        '/parent/profile',
        '/parent/children',
        '/parent/bookings',
        '/parent/orders',
        '/parent/youbi',
        '/parent/messages'
      ];

      // 检查路径是否在可访问列表中
      return accessibleRoutes.some(accessibleRoute => routePath.startsWith(accessibleRoute));
    };

    // 显示无权限提示
    const showPermissionDeniedAlert = (menuName) => {
      alert(`您没有权限访问"${menuName}"功能。请联系管理员获取相应权限。`);
    };

    // 登出函数
    const logout = async () => {
      await authStore.logout();
      await router.push('/login');
    };

    // 初始化：设置当前路由为激活的标签页
    onMounted(() => {
      if (route.path && route.path.startsWith('/parent')) {
        // 如果是家长相关路径，设置为当前激活的标签页
        if (route.path === '/parent' || route.path === '/parent/profile') {
          activeTab.value = '/parent/profile';
        } else {
          const menuName = route.path.split('/').pop() || 'Dashboard';
          const title = t(`message.${menuName.toLowerCase()}`) || menuName;
          openTab(route.path, title);
        }
      }
    });

    return {
      sidebarCollapsed,
      expandedCategories,
      openedTabs,
      activeTab,
      openTab,
      switchTab,
      closeTab,
      toggleSidebar,
      toggleCategory,
      isExpanded,
      handleMenuClick,
      isActiveMenu,
      switchToDefaultTab,
      isDefaultTabActive,
      logout,
      t,
      isAccessibleRoute,
      showPermissionDeniedAlert
    };
  }
};
</script>

<style scoped>
.parent-layout {
  height: 100%; /* 让组件填满父级容器 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.layout-container {
  display: flex;
  flex: 1; /* 占据所有可用空间 */
  overflow: hidden; /* 防止出现滚动条 */
}

.sidebar {
  width: 256px;
  background-color: white;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  display: flex;
  flex-direction: column;
  z-index: 99;
  height: 100%;
  justify-content: flex-start; /* 确保内容在顶部对齐 */
  position: relative; /* 为切换按钮定位 */
  flex-shrink: 0; /* 防止侧边栏被压缩 */
}

.sidebar.collapsed {
  width: 60px;
  flex-shrink: 0;
}

.toggle-btn {
  position: absolute;
  top: 50%;
  right: -10px;
  transform: translateY(-50%);
  background: #1890ff;
  color: white;
  width: 20px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 100;
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar.collapsed .menu-text {
  display: none;
}

.sidebar.collapsed .menu-icon {
  margin-right: 0;
  font-size: 18px;
}

.menu-nav {
  padding: 0 0.5em; /* 上下为0，左右为0.5em */
  margin: 0; /* 去除所有外边距 */
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  width: 100%; /* 确保占满侧边栏宽度 */
}

/* 菜单项分组样式 */
.menu-group {
  padding: 0;
  margin: 0; /* 移除所有边距 */
}

.menu-group-title {
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 减少左右边距，从24px改为16px */
  color: #595959;
  font-weight: bold;
  background-color: #f5f5f5;
  border-radius: 0; /* 去除圆角使整个菜单项看起来更连贯 */
  margin: 0; /* 去除所有边距 */
  cursor: pointer;
  width: 100%; /* 确保占满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
  justify-content: space-between; /* 两端对齐使内容分布在两侧，填满宽度 */
}

.menu-group-title .menu-icon {
  margin-right: 12px;
  font-size: 16px;
}

.submenu {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 1000px;
  overflow: hidden;
  transition: max-height 0.3s ease; /* 添加过渡动画 */
}

.submenu.hidden {
  max-height: 0; /* 当隐藏时，高度为0 */
}

.submenu .menu-item {
  padding-left: 44px; /* 为子菜单项添加更多左边距 */
  justify-content: space-between; /* 确保子菜单项也铺满宽度 */
}

.menu-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left; /* 文字左对齐 */
  width: calc(100% - 1em); /* 宽度为100%减去左右各0.5em的padding，共1em */
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 减少左右边距，从24px改为16px */
  color: #595959;
  text-decoration: none;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  text-align: left;
  justify-content: space-between; /* 两端对齐，使内容分布在两端，填满宽度 */
  border-radius: 0; /* 去掉圆角，让菜单项铺满整个宽度 */
  margin: 0; /* 去除菜单项之间的所有边距 */
  width: 100%; /* 确保菜单项填满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}

.menu-item:hover {
  background-color: #f0f9ff;
  color: #409eff;
  border-left: 3px solid #409eff;
}

.menu-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  border-left: 3px solid #409eff;
  font-weight: 500;
}

.menu-icon {
  margin-right: 8px;
  font-size: 16px;
  width: 24px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-text {
  flex: 1; /* 使文本占据剩余空间 */
  font-size: 14px;
  text-align: left; /* 文字左对齐 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  margin-right: 8px; /* 与右侧展开图标保持一定距离 */
}

.expand-icon {
  margin-left: auto; /* 自动边距使图标推到右侧 */
  transition: transform 0.3s ease;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px; /* 确保有足够的空间显示箭头 */
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.root-menu-title {
  display: flex;
  align-items: center;
  padding: 16px 16px; /* 减少左右边距，从24px改为16px */
  color: #1890ff;
  font-weight: bold;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  margin: 0; /* 去除所有边距 */
  width: 100%; /* 确保占满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
}

.main-content {
  flex: 1; /* 占据所有可用空间 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  min-width: 0; /* Flex子项目的最小尺寸设置为0 */
  overflow: hidden; /* 防止出现不必要的滚动 */
  margin: 0;
  padding: 0;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.tabs-bar {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0;
  flex-shrink: 0;
  margin: 0;
  border: none;
  box-shadow: none;
  min-height: 40px;
}

.tab-item {
  padding: 8px 20px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-bottom: none;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  border-top: 1px solid #e8e8e8;
  margin-right: 4px;
  cursor: pointer;
  position: relative;
  display: inline-flex;
  align-items: center;
  margin: 0;
  line-height: normal;
}

.tab-item.active {
  background-color: white;
  border-bottom: 1px solid white;
  color: #1890ff;
  font-weight: 500;
  margin-bottom: -1px;
}

.tab-close {
  margin-left: 8px;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 12px;
}

.tab-close:hover {
  background-color: #ccc;
  color: white;
}

.content-area {
  flex: 1; /* 占据所有可用空间 */
  overflow-y: auto;
  padding: 16px; /* 减少内边距，从24px改为16px */
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-top: none;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  min-height: 0; /* 允许内容区域在小空间内滚动 */
  overflow: auto;
  margin: 0;
}

.tab-content {
  height: 100%;
}

.tab-content-inner {
  height: 100%;
}

.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 200px;
  color: #909399;
}

.default-component, .error-component {
  padding: 20px;
  text-align: center;
  color: #909399;
}

@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
}
</style>